﻿using CSRedis;
using Newtonsoft.Json;
using QskjDownloadVideoAddWatermark.Dto;
using QskjLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace QskjDownloadVideoAddWatermark.Service
{
    public static class DownloadUpdate
    {
        #region 添加水印处理 
        #endregion
        /// <summary>
        /// 下载记录查询-启动下载-刷新进度
        /// </summary>
        public static void GetVideoDataWatermark()
        {
            try
            {
                List<DownloadVideoFileDto> list = new List<DownloadVideoFileDto>();
                string dtS = DateTime.Now.ToString("yyyy-MM-dd"), dte = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                string sql = $@"select a.Id,a.userName,a.licensePlate,a.channel,a.deviceId,a.url,a.status,a.schedule,a.createtimedts,a.createtimedte,a.createtimeFiledts,a.createtimeFiledte,a.createtime,a.downloadType,a.fileSize,a.operateType,a.remarks,a.playId,a.ftpurl,a.filewatermarkinfo,b.supplier,a.SerialMark
                                from qskj.B_DownloadVideoFile a
                                join qskj.B_Taxi b on a.licensePlate=b.license_plate
                                where a.createtime>='{dtS}' and a.createtime<'{dte}' and description2 ='ftpurlsuccess' and watermarkStatus=0"; //and b.supplier!='hk' 
                DataTable dt = MySqlHelper.GetDataTable(System.Data.CommandType.Text, sql);
                foreach (DataRow row in dt.Rows)
                {
                    DownloadVideoFileDto dvf = new DownloadVideoFileDto();
                    dvf.Id = Convert.ToInt32(row["Id"]);
                    dvf.userName = row["userName"] == DBNull.Value ? "" : row["userName"].ToString();
                    dvf.licensePlate = row["licensePlate"] == DBNull.Value ? "" : row["licensePlate"].ToString();
                    dvf.channel = row["channel"] == DBNull.Value ? "" : row["channel"].ToString();
                    dvf.deviceId = row["deviceId"] == DBNull.Value ? "" : row["deviceId"].ToString();
                    dvf.createtimeFiledts = Convert.ToDateTime(row["createtimeFiledts"]).ToString("yyyy-MM-ddTHH:mm:ss");
                    dvf.createtimeFiledte = Convert.ToDateTime(row["createtimeFiledte"]).ToString("yyyy-MM-ddTHH:mm:ss");
                    dvf.url = row["url"] == DBNull.Value ? "" : row["url"].ToString();
                    dvf.ftpurl = row["ftpurl"] == DBNull.Value ? "" : row["ftpurl"].ToString();
                    dvf.fileSize = row["fileSize"] == DBNull.Value ? "" : row["fileSize"].ToString();
                    dvf.status = row["status"] == DBNull.Value ? "" : row["status"].ToString();
                    dvf.remarks = row["remarks"] == DBNull.Value ? "" : row["remarks"].ToString();
                    dvf.playId = row["playId"] == DBNull.Value ? "" : row["playId"].ToString();
                    dvf.filewatermarkinfo = row["filewatermarkinfo"] == DBNull.Value ? "" : row["filewatermarkinfo"].ToString();
                    dvf.supplier = row["supplier"] == DBNull.Value ? "" : row["supplier"].ToString();
                    dvf.SerialMark = row["SerialMark"] == DBNull.Value ? "" : row["SerialMark"].ToString();
                    list.Add(dvf);
                    {
                        Task.Factory.StartNew(() =>
                        {
                            string sqlUpdateUrl = $@"update qskj.B_DownloadVideoFile set watermarkStatus=2 where id={dvf.Id}";
                            MySqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdateUrl);
                            DownloadVideoDataByFtpWaterMark(dvf);//直连车辆录像视频水印处理
                        });
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("下载记录查询信息异常" + JsonConvert.SerializeObject(e));
            }
        }
        /// <summary>
        /// 直连车下载视频上传到视图库
        /// </summary>
        /// <param name="dvf">下载请求记录</param>
        public static async void DownloadVideoDataByFtpWaterMark(DownloadVideoFileDto dvf)
        {
            try
            {
                CSRedisClient cSRedisClient = RedisHelp.GetInstance();
                string strToken = cSRedisClient.Get("webRtcToken"), downloadUrlStr = cSRedisClient.Get("downloadRecord"), fileUrlStr = cSRedisClient.Get("queryRecordProgressAndURL"), ftpUrlInfo = cSRedisClient.Get("ftpUrlInfo");
                PlayUrlToken videoUrlDto = new PlayUrlToken();
                if (string.IsNullOrEmpty(strToken) || string.IsNullOrEmpty(downloadUrlStr) || string.IsNullOrEmpty(fileUrlStr) || string.IsNullOrEmpty(ftpUrlInfo))
                {
                    List<S_SystemUrl> systemUrls = new List<S_SystemUrl>();
                    string sqlUrl = $@"select name,keyname,url,groupname from qskj.S_SystemUrl";
                    DataTable dtUrl = MySqlHelper.GetDataTable(CommandType.Text, sqlUrl);
                    foreach (DataRow dr in dtUrl.Rows)
                    {
                        S_SystemUrl s = new S_SystemUrl();
                        s.Name = dr["name"].ToString();
                        s.KeyName = dr["keyname"].ToString();
                        s.Url = dr["url"].ToString();
                        s.GroupName = dr["groupname"].ToString();
                        systemUrls.Add(s);
                    }
                    S_SystemUrl? systemUrl = systemUrls.FirstOrDefault(p => p.KeyName == "webRtcNew1");
                    if (systemUrl == null)
                    {
                        Console.WriteLine("系统WebRtc链接未设置");
                    }
                    string[]? str = systemUrl.Url?.Split(';');
                    //读取token数据
                    strToken = HttpHelper.GetWebRtcToken(str[0], str[1], str[2]).Result;
                    WebRtcToken? obj = JsonConvert.DeserializeObject<WebRtcToken>(strToken);
                    strToken = obj.data;
                    cSRedisClient.Set("webRtcToken", obj.data, 1 * 60 * 60 * 10);//十小时过期
                    S_SystemUrl? downloadUrl = systemUrls.FirstOrDefault(p => p.KeyName == "downloadRecord");
                    downloadUrlStr = downloadUrl.Url;
                    cSRedisClient.Set("downloadRecord", downloadUrl.Url, 1 * 60 * 60 * 10);//十小时过期
                    S_SystemUrl? fileUrl = systemUrls.FirstOrDefault(p => p.KeyName == "queryRecordProgressAndURL");
                    fileUrlStr = fileUrl.Url;
                    cSRedisClient.Set("queryRecordProgressAndURL", fileUrl.Url, 1 * 60 * 60 * 10);//十小时过期
                    S_SystemUrl? ftpInfo = systemUrls.FirstOrDefault(p => p.KeyName == "videoHisDownload");
                    ftpUrlInfo = ftpInfo.Url;
                    cSRedisClient.Set("ftpUrlInfo", ftpInfo.Url, 1 * 60 * 60 * 10);//十小时过期
                }
                string[] ftpInfoArr = ftpUrlInfo.Split(';');
                string[] fileInfo = dvf.ftpurl.Split('/');
                string localFilePath = AppDomain.CurrentDomain.BaseDirectory + "videoFile_" + fileInfo.LastOrDefault(), watermarkFilePath = AppDomain.CurrentDomain.BaseDirectory + "videoFileWatermark_" + fileInfo.LastOrDefault();
                Console.WriteLine(localFilePath);
                string ftpServer = "ftp://yourftpserver.com";
                string username = ftpInfoArr[2];
                string password = ftpInfoArr[3];
                string[] filetype = localFilePath.Split('.');
                string filetype1 = filetype.LastOrDefault();
                string filename1 = fileInfo.LastOrDefault(); string bt = DateTime.Now.ToString("yyyyMMddHHmmss");
                string strKey = bt + DateTime.Now.Ticks;

                #region ftp文件下载到本地
                //if (!File.Exists(localFilePath))
                //{
                //    try
                //    {
                //        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(dvf.ftpurl);
                //        request.Method = WebRequestMethods.Ftp.DownloadFile;
                //        request.Credentials = new NetworkCredential(username, password);

                //        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                //        Stream responseStream = response.GetResponseStream();
                //        if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                //        {
                //            Console.WriteLine("FTP文件还不存在");
                //            return;
                //        }

                //        FileStream localFileStream = new FileStream(localFilePath, FileMode.Create);
                //        byte[] buffer = new byte[1024 * 10 * 10];
                //        int bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                //        // Write the downloaded data to a local file.
                //        while (bytesRead > 0)
                //        {
                //            localFileStream.Write(buffer, 0, bytesRead);
                //            bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                //        }
                //        // Close the response and stream objects
                //        response.Close();
                //        localFileStream.Close();
                //    }
                //    catch (Exception e)
                //    {
                //        Console.WriteLine("ftp下载文件到本地" + e.Message + JsonConvert.SerializeObject(e));
                //    }
                //}
                #endregion
                #region ftp文件Http下载到本地
                if (!File.Exists(localFilePath))
                {
                    string status = "";
                    try
                    {
                        #region http检测文件是否存在
                        try
                        {
                            List<string> strList = dvf.ftpurl.Split('/').ToList();
                            if (dvf.SerialMark != "0")
                            {
                                Console.WriteLine(strList.Last() + "FTP上传文件未结束");
                                return;
                            }
                            string httpUrl = "http://192.168.3.116:9100/" + strList.Last();
                            {
                                long lastSize = 0, currentSize = 0; bool isIncreasing = true;
                                while (isIncreasing)
                                {
                                    long? fileLength = GetRemoteFileSizeAsync(httpUrl).Result;
                                    currentSize = fileLength == null ? 0 : (long)fileLength / 1024;
                                    isIncreasing = currentSize > lastSize;
                                    lastSize = currentSize;
                                    Console.WriteLine(strList.Last() + "currentSize文件大小" + currentSize + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                    Thread.Sleep(1000 * 5);
                                }
                                Console.WriteLine(strList.Last() + "文件大小" + lastSize + isIncreasing);
                            }
                            using (HttpClient client = new HttpClient())
                            {
                                // 配置客户端
                                client.Timeout = TimeSpan.FromSeconds(15);
                                client.DefaultRequestHeaders.Add("User-Agent", "File Checker");
                                // 第一步：尝试 HEAD 请求
                                var headResponse = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, httpUrl));
                                // 分析结果
                                switch (headResponse.StatusCode)
                                {
                                    case System.Net.HttpStatusCode.OK:
                                        status = "OK";
                                        break;
                                    case System.Net.HttpStatusCode.NotFound:
                                        status = "NotFound";
                                        break;
                                    case System.Net.HttpStatusCode.Forbidden:
                                        status = "NoPermission";
                                        break;
                                    default:
                                        status = "Unknown";
                                        break;
                                }
                            }
                            Console.WriteLine(strList.Last() + "文件检测结果：" + status + "  " + httpUrl);
                            if (status != "OK")
                            {
                                string sqlUpdateKey = $@"update qskj.B_DownloadVideoFile set status=4,description='file is {status}' where id={dvf.Id}";
                                MySqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdateKey);
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"文件检测异常：{ex.Message}");
                        }
                        #endregion
                        if (status != "OK")
                        {
                            Console.WriteLine(status);
                            return;
                        }
                        try
                        {
                            string sqlUpdateKey = $@"update qskj.B_DownloadVideoFile set playId='{strKey}',status=2,description='ftpsuccess' where id={dvf.Id}";
                            MySqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdateKey);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("更新下载状态失败：" + e.Message);
                        }
                        string dsStr = string.Empty;
                        try
                        {
                            Console.WriteLine("开始下载...");
                            List<string> strList = dvf.ftpurl.Split('/').ToList();
                            string httpUrl = "http://192.168.3.116:9100/" + strList.Last();
                            await DownloadFileAsync(httpUrl, localFilePath);
                            Console.WriteLine($"下载完成！文件已保存至：{localFilePath}");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"下载失败：{ex.Message}");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ftp下载文件到本地1" + e.Message + JsonConvert.SerializeObject(e));
                        return;
                    }
                }
                #endregion
                #region 水印业务处理
                {
                    if (File.Exists(localFilePath))
                    {
                        string strWater = "";
                        if (string.IsNullOrWhiteSpace(dvf.filewatermarkinfo))
                        {
                            strWater = dvf.userName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                        }
                        else
                        {
                            string[] wi = dvf.filewatermarkinfo.Split(',');
                            if (string.IsNullOrWhiteSpace(dvf.filewatermarkinfo.Split(',')[0]))
                            {
                                strWater = dvf.userName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                            }
                            else
                            {
                                strWater = dvf.filewatermarkinfo.Split(',')[0] + DateTime.Now.ToString("yyyyMMddHHmmss");
                            }
                            string transVideo = AppDomain.CurrentDomain.BaseDirectory + "videoFileC_" + fileInfo.LastOrDefault();
                            if (dvf.supplier == "hk")
                            {
                                //VideoToMp4(localFilePath, transVideo); Thread.Sleep(1000);
                                //Console.WriteLine(transVideo); 
                                //try
                                //{
                                //    #region 上传文件信息
                                //    var dataInfoRes = PostFileDataInfo(strKey, "mp4", fileInfo.LastOrDefault());
                                //    DataInfo responseDataInfo = new DataInfo();
                                //    responseDataInfo = JsonConvert.DeserializeObject<DataInfo>(dataInfoRes.Result);
                                //    #endregion
                                //    #region 上传文件 
                                //    {
                                //        var dataRes = PostFileData(strKey, transVideo);//上传转码后的视频文件
                                //        DataFile responseData = new DataFile();
                                //        responseData = JsonConvert.DeserializeObject<DataFile>(dataRes.Result);
                                //    }
                                //    #endregion
                                //}
                                //catch (Exception ex)
                                //{
                                //    Console.WriteLine("qskj--hk视频转码上传文件到视图库" + ex);
                                //}
                                AddTextWatermarkHk(localFilePath, watermarkFilePath, strWater, strKey, fileInfo.LastOrDefault(), bt);
                            }
                            else
                            {
                                AddTextWatermark(localFilePath, watermarkFilePath, strWater, strKey, fileInfo.LastOrDefault(), wi, bt);
                            }
                        }
                    }
                }
                #endregion

                #region 视图库地址查询
                try
                {
                    string url = GetUrl(strKey, filetype1, bt);
                    if (!string.IsNullOrWhiteSpace(url))
                    {
                        #region 获取文件大小  
                        long fileSizeLocal = 0;
                        FileInfo fileSizeInfo = new FileInfo(localFilePath);
                        if (fileSizeInfo.Exists)
                        {
                            long fileSize = fileSizeInfo.Length; // 获取文件大小，单位是字节
                            fileSizeLocal = (fileSize / 1024) / 1024;//换算成MB 
                            //删除本地资源文件
                            File.Delete(localFilePath);
                            Console.WriteLine($@"删除FTP视频文件：{localFilePath}");
                            File.Delete(watermarkFilePath);
                            Console.WriteLine($@"删除FTP水印视频文件：{watermarkFilePath}");
                        }
                        #endregion
                        string sqlUpdateUrl = $@"update qskj.B_DownloadVideoFile set url='{url}',watermarkUrl='{url}',watermarkStatus=1,watermarkplayId='{strKey}' where id={dvf.Id}";
                        MySqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdateUrl);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("ftp文件视图库地址查询" + e.Message);
                }
                #endregion
            }
            catch (Exception e)
            {
                Console.WriteLine("启动Ftp下载信息异常" + JsonConvert.SerializeObject(e));
            }
        }
        public static string AddTextWatermark(string inFile, string outputVideoPath, string watermarkText, string strKey, string fileInfo, string[] wi, string bt)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(wi[5]))
                {
                    wi[5] = "white";
                }
                //string wm = $@"{watermarkText}_{DateTime.Now.ToString("yyyyMMddHHmmss")}_{watermarkText}_{DateTime.Now.ToString("yyyyMMddHHmmss")}";//水印文本信息
                string wm = $@"{watermarkText}";//水印文本信息
                string fa = AppDomain.CurrentDomain.BaseDirectory;
                int fz = Convert.ToInt32(wi[1]) * 2;
                //string arguments = $"-i " + inFile + " -filter_complex \"color=White:s=1200x700[v1];[v1]drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 90 + ":fontsize=" + wi[1] + ":alpha=" + wi[2] + ",drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 150 + ":y=" + 360 + ":fontsize=" + wi[1] + ":alpha=" + wi[2] + ",drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 600 + ":fontsize=" + wi[1] + ":alpha=" + wi[2] + "[o1];[o1]rotate=" + wi[3] + ":fillcolor=White@0[o1];[o1]colorkey=White:0.01:1[o2];[0:v][o2]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1\" -y " + outputVideoPath;// + " -timeout 1000000*600"
                string arguments = $"-i " + inFile + " -filter_complex \"color=" + wi[5] + ":s=1920x1080[v1];[v1]drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 30 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 30 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 600 + ":y=" + 30 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 900 + ":y=" + 30 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1200 + ":y=" + 30 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1400 + ":y=" + 30 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 1800 + ":y=" + 30 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 210 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 210 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 600 + ":y=" + 210 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 900 + ":y=" + 210 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1200 + ":y=" + 210 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1400 + ":y=" + 210 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 1800 + ":y=" + 210 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 390 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 390 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 600 + ":y=" + 390 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 900 + ":y=" + 390 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1200 + ":y=" + 390 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1400 + ":y=" + 390 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 1800 + ":y=" + 390 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 570 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 570 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 600 + ":y=" + 570 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 900 + ":y=" + 570 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1200 + ":y=" + 570 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1400 + ":y=" + 570 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 1800 + ":y=" + 570 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 750 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 750 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 600 + ":y=" + 750 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 900 + ":y=" + 750 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1200 + ":y=" + 750 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1400 + ":y=" + 750 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 1800 + ":y=" + 750 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 930 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 930 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 600 + ":y=" + 930 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 900 + ":y=" + 930 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1200 + ":y=" + 930 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1400 + ":y=" + 930 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 1800 + ":y=" + 930 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 1110 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 1110 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 600 + ":y=" + 1110 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 900 + ":y=" + 1110 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1200 + ":y=" + 1110 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1400 + ":y=" + 1110 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 1800 + ":y=" + 1110 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 1290 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 1290 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 600 + ":y=" + 1290 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 900 + ":y=" + 1290 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1200 + ":y=" + 1290 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    //+ "SIMSUN.TTC:text='" + wm + "':x=" + 1400 + ":y=" + 1290 + ":fontsize=" + fz + ":alpha=" + wi[2] + ",drawtext=fontfile=" + fa
                    + "SIMSUN.TTC:text='" + wm + "':x=" + 1800 + ":y=" + 1290 + ":fontsize=" + fz + ":alpha=" + wi[2] + "[o1];[o1]rotate=" +  Convert.ToInt32(wi[3])  + "*PI/180:fillcolor=" + wi[5] + "@0[o1];[o1]colorkey=" + wi[5] + ":0.01:1[o2];[0:v][o2]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1\" -y " + outputVideoPath;// + " -timeout 1000000*600"
                Console.WriteLine(arguments);
                //{
                //    arguments = $"ffmpeg -i {inFile} -vf \"drawtext=fontfile={fa}SIMSUN.TTC:text='{wm}':fontcolor={wi[5]}:fontsize={fz}:alpha={wi[2]}:x=10:y=10\" -codec:a copy {outputVideoPath}";
                //}
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "ffmpeg",
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true
                };
                using (Process process = Process.Start(startInfo))
                {
                    process.WaitForExit(); // 等待FFmpeg进程执行完成

                    try
                    {

                        #region 上传文件信息
                        var dataInfoRes = PostFileDataInfo(strKey, "mp4", fileInfo, bt);
                        DataInfo responseDataInfo = new DataInfo();
                        responseDataInfo = JsonConvert.DeserializeObject<DataInfo>(dataInfoRes.Result);
                        #endregion
                        #region 上传文件 
                        {
                            var dataRes = PostFileData(strKey, outputVideoPath);//上传加载水印后的视频文件
                            DataFile responseData = new DataFile();
                            responseData = JsonConvert.DeserializeObject<DataFile>(dataRes.Result);
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("qskj视频添加水印并上传文件到视图库" + ex);
                    }
                    return "1";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("qskj视频添加水印" + e);
                return "0";
            }
        }
        public static string AddTextWatermarkHk(string inFile, string outputVideoPath, string watermarkText, string strKey, string fileInfo, string bt)
        {
            try
            {
                string wm = $@"{watermarkText}_{DateTime.Now.ToString("yyyyMMddHHmmss")}_{watermarkText}_{DateTime.Now.ToString("yyyyMMddHHmmss")}";//水印文本信息
                //ffmpeg - i input.mp4 - filter_complex "color=s=200x400:c=black@0[c];[c]drawtext=text='水印文字':fontfile=./simhei.ttf:fontsize=48:fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2:alpha=1,rotate=2*PI*t:c=none[txt];[0:v][txt]overlay=x='(W-w)*abs(sin(t*0.2))':y='(H-h)*(1-abs(sin(t*0.2)))':shortest=1" - codec:a copy output.mp4
                string arguments = $"-i " + inFile + " -filter_complex color=s=200x400:c=black@0[c];[c]drawtext=text='" + wm + "':fontsize=48:fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2:alpha=1,rotate=2*PI*t:c=none[txt];[0:v][txt]overlay=x='(W-w)*abs(sin(t*0.2))':y='(H-h)*(1-abs(sin(t*0.2)))':shortest=1 - codec:a copy " + outputVideoPath;
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "ffmpeg",
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true
                };
                using (Process process = Process.Start(startInfo))
                {
                    process.WaitForExit(); // 等待FFmpeg进程执行完成

                    try
                    {

                        #region 上传文件信息
                        var dataInfoRes = PostFileDataInfo(strKey, "mp4", fileInfo, bt);
                        DataInfo responseDataInfo = new DataInfo();
                        responseDataInfo = JsonConvert.DeserializeObject<DataInfo>(dataInfoRes.Result);
                        #endregion
                        #region 上传文件 
                        {
                            var dataRes = PostFileData(strKey, outputVideoPath);//上传加载水印后的视频文件
                            DataFile responseData = new DataFile();
                            responseData = JsonConvert.DeserializeObject<DataFile>(dataRes.Result);
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("qskj视频添加水印并上传文件到视图库" + ex);
                    }
                    return "1";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("qskj视频添加水印" + e);
                return "0";
            }
        }
        public static string GetUrl(string key, string ft, string begintime)
        {
            string url = string.Empty;
            try
            {
                string videoUrl = string.Empty, imageUrl = string.Empty;
                if (ft == "mp4")
                {
                    try
                    {
                        DataVideoUrl videoData = new DataVideoUrl();
                        videoUrl = GetFileDataUrl(key, begintime).Result;
                        videoData = JsonConvert.DeserializeObject<DataVideoUrl>(videoUrl);
                        if (!string.IsNullOrEmpty(videoData?.VideoSliceListObject?.VideoSlice[0]?.VideoSliceInfo?.StoragePath))
                        {
                            url = videoData?.VideoSliceListObject?.VideoSlice[0]?.VideoSliceInfo?.StoragePath;//视图库视频地址信息
                        }
                        return url;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "Ftp视图库视频地址查询异常：" + e.Message);
                        return url;
                    }
                }
                else
                {
                    try
                    {
                        DataImageUrl imageData = new DataImageUrl();
                        imageUrl = GetImageFileDataUrl(key).Result;
                        imageData = JsonConvert.DeserializeObject<DataImageUrl>(imageUrl);
                        if (!string.IsNullOrEmpty(imageData?.ImageListObject?.Image[0]?.ImageInfo?.StoragePath))
                        {
                            url = imageData?.ImageListObject?.Image[0]?.ImageInfo?.StoragePath;
                        }
                        return url;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "Ftp视图库图片地址查询异常：" + e.Message);
                        return url;
                    }

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "Ftp视图库证据地址查询异常：" + e.Message);
                return url;
            }
        }
        /// <summary>
        /// 视图库视频文件查询
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetFileDataUrl(string key, string begintime)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, $@"http://192.168.3.223:8000/VIID/VideoSlices?VideoID={key}&BeginTime ={begintime}");
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        /// <summary>
        /// 视图库图片文件查询
        /// </summary>
        /// <param name="key">Id</param>
        /// <returns></returns>
        public static async Task<string> GetImageFileDataUrl(string key)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, "http://192.168.3.223:8000/VIID/Images?ImageID=" + key);
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        #region 视图库相关操作接口
        /// <summary>
        /// 上传视图库数据结构
        /// </summary> 
        /// <param name="key">Id</param>
        /// <param name="s">格式</param>
        /// <param name="n">文件名</param>
        /// <returns></returns>
        public static async Task<string> PostFileDataInfo(string key, string s, string n, string bt)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.3.223:8000/VIID/VideoSlices");
            var content = new StringContent("{\r\n    \"VideoSliceListObject\": {\r\n        \"VideoSlice\": [\r\n            {\r\n                \"VideoSliceInfo\": {\r\n                    \"VideoID\": \"" + key + "\",\r\n                    \"InfoKind\": 0,\r\n                    \"VideoSource\": \"\",\r\n                    \"FileFormat\": \"" + s + "\",\r\n                    \"CodedFormat\": \"\",\r\n                    \"AudioFlag\": 0,\r\n                    \"Title\": \"" + n + "\",\r\n                    \"ContentDescription\": \"\",\r\n                    \"ShotPlaceCode\": \"\",\r\n                    \"VideoLen\": 0.0,\r\n                    \"BeginTime\": \"" + bt + "\",\r\n                    \"EndTime\": \"\",\r\n                    \"TimeErr\": 0,\r\n                    \"Width\": 0,\r\n                    \"Height\": 0\r\n                }\r\n            }\r\n        ]\r\n    }\r\n}", null, "application/json");
            request.Content = content;
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        /// <summary>
        /// 上传视图库视频文件
        /// </summary>
        /// <returns></returns>
        public static async Task<string> PostFileData(string key, string filePath = null)
        {
            using (FileStream file = File.OpenRead(filePath))
            {
                var client = new HttpClient();
                var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.3.223:8000/VIID/FileData/" + key + "/VideoSlices");
                //request.Content = (content);
                //content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                request.Content = new StreamContent(file);
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                var response = await client.SendAsync(request);
                response.EnsureSuccessStatusCode();
                string res = await response.Content.ReadAsStringAsync();
                return res;
            }
        }
        public static async Task<long?> GetRemoteFileSizeAsync(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    // 发送 HEAD 请求
                    var response = await client.SendAsync(
                        new HttpRequestMessage(HttpMethod.Head, url)
                    );

                    response.EnsureSuccessStatusCode();

                    // 从响应头获取文件大小
                    return response.Content.Headers.ContentLength;
                }
                catch
                {
                    return null;
                }
            }
        }
        #region http下载
        static async Task DownloadFileAsync(string url, string filePath)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                // 设置超时（可选）
                httpClient.Timeout = TimeSpan.FromMinutes(5);
                // 发送GET请求
                using (HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode(); // 确保响应成功
                    // 创建文件目录（如果不存在）
                    string directory = Path.GetDirectoryName(filePath);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }
                    // 写入文件流
                    using (Stream contentStream = await response.Content.ReadAsStreamAsync(),
                                  fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        await contentStream.CopyToAsync(fileStream);
                    }
                }
            }
        }
        #endregion
        #endregion 
    }
}
